<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\pay\model;

use think\facade\Db;
use think\Model;
use tree\Tree;

class GoodsModel extends Model
{
    /**
     * Notes:返回商品分类
     * User: 
     * DateTime: 2021/4/14 17:03
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsCate()
    {
        $categories = Db::name("category")
            ->field("id,category_name")
            ->where('delete_time', 0)
            ->select()
            ->toArray();
        return $categories;
    }

    /**
     * Notes:分类树形结构
     * User: 
     * DateTime: 2021/3/5 14:01
     * @param array $where
     * @param int $currentIds
     * @param string $tpl
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function navTableTree($currentIds = 0, $tpl = '', $where = [])
    {
        $categories = Db::name("goods")
            ->alias('r')
            ->join('goods_category n', 'n.id=r.category_id', "right")
            ->where($where)
            ->field(['n.*,count(r.id) as count'])
            ->group("n.id")
            ->order("n.list_order ASC")
            ->select()->toArray();

        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        if (!is_array($currentIds)) {
            $currentIds = [$currentIds];
        }

        $newCategories = [];
        foreach ($categories as $item) {
            if (cmf_auth_check(cmf_get_current_admin_id(), 'admin/Goods/index?id=' . $item['id'])) {
                $item['parent_id_node'] = ($item['parent_id']) ? ' class="child-of-node-' . $item['parent_id'] . '"' : '';
                $item['style'] = empty($item['parent_id']) ? '' : 'display:none;';
                $item['checked'] = in_array($item['id'], $currentIds) ? "checked" : "";
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['count'] = $item['count'];
                $item['url'] = cmf_url('admin/Goods/goodsCategory', ['id' => $item['id']]);
                $act = "onclick=addAction" . "('" . "getGoodsList/id/" . $item['id'] . ".html')";
                $add = "onclick=addAction" . "('" . "addCategory/parent/" . $item['id'] . ".html')";
                $edit = "onclick=addAction" . "('" . "editCategory/id/" . $item['id'] . ".html')";
                $item['str_action'] = '<a class="btn btn-xs btn-primary" href="javascript:;" ' . $act . '>商品管理</a> ';
                $item['str_action'] .= '<a class="btn btn-xs btn-primary" href="javascript:;" ' . $add . '>添加子分类</a> ';
                $item['str_action'] .= '<a class="btn btn-xs btn-primary" href="' . url("Goods/editCategory", ["id" => $item['id']]) . '">' . lang('EDIT') . '</a> ';
                $item['str_action'] .= '<a class="btn btn-xs btn-danger js-ajax-delete" href="' . url("Goods/deleteCategory", ["id" => $item['id']]) . '">' . lang('DELETE') . '</a> ';
                array_push($newCategories, $item);
            }
        }
        $tree->init($newCategories);
        if (empty($tpl)) {
            $tpl = " <tr id='node-\$id' \$parent_id_node style='\$style' data-parent_id='\$parent_id' data-id='\$id'>
                        <td style='padding-left:20px;'><input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]' value='\$id' data-parent_id='\$parent_id' data-id='\$id'></td>
                        <td>\$id</td>
                        <td><img width='25' height='25' src='\$img'/></td>
                        <td>\$spacer \$category_name</td>
                        <td>\$count</td>
                        <td>\$list_order</td>
                        <td>\$create_time</td>
                        <td>\$str_action</td>
                    </tr>";
        }
        $treeStr = $tree->getTree(0, $tpl);
        return $treeStr;
    }

    /**
     * Notes:商品列表
     * User: 
     * DateTime: 2021/4/14 17:01
     * @param int $currentIds
     * @param string $tpl
     * @param array $where
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function goodsTableTree($currentIds = 0, $tpl = '', $where = [])
    {
        $where['delete_time'] = 0;
        $categories = Db::name("goods")->where($where)->select()->toArray();
        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';
        if (!is_array($currentIds)) {
            $currentIds = [$currentIds];
        }
        $newCategories = [];
        foreach ($categories as $item) {
            if (cmf_auth_check(cmf_get_current_admin_id(), 'admin/Goods/index?id=' . $item['id'])) {
                $item['parent_id'] = 0;
                $item['parent_id_node'] = ($item['parent_id']) ? ' class="child-of-node-' . $item['parent_id'] . '"' : '';
                $item['style'] = empty($item['parent_id']) ? '' : 'display:none;';
                $item['checked'] = in_array($item['id'], $currentIds) ? "checked" : "";
                array_push($newCategories, $item);
            }
        }
        $tree->init($newCategories);
        if (empty($tpl)) {
            $tpl = " <tr id='node-\$id' \$parent_id_node style='\$style' data-parent_id='\$parent_id' data-id='\$id'>
                        <td style='padding-left:20px;'><input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]' value='\$id' data-parent_id='\$parent_id' data-id='\$id'></td>
                        <td>\$id</td>
                        <td>\$goods_name</td>
                        <td>\$price</td>
                    </tr>";
        }
        $treeStr = $tree->getTree(0, $tpl);
        return $treeStr;
    }

    /**
     * Notes:添加商品分类
     * User: 
     * DateTime: 2021/4/12 11:48
     * @param $data
     * @return int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addNav($data)
    {
        if (empty($data['img'])) {
            unset($data['img']);
        }
        //拼接path
        if ($data['parent_id'] == 0) {
            $path = 0;
        } else {
            $parent = Db::name("goods_category")->where(["id" => $data['parent_id']])->field("path")->where(["delete_time" => 0])->find();
            if ($parent) {
                $path = $parent['path'] . "," . $data['parent_id'];
            } else {
                $path = $data['parent_id'];
            }
        }
        $data['path'] = $path;
        $data['create_time'] = time();
        $result = Db::name("goods_category")->insert($data);
        return $result;
    }

    /**
     * Notes:分组修改执行
     * User: 
     * DateTime: 2021/3/5 13:39
     * @param $data
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editNav($data)
    {
        if (empty($data['img'])) {
            unset($data['img']);
        }
        $id = intval($data['id']);
        $parentId = intval($data['parent_id']);
        if (!cmf_auth_check(cmf_get_current_admin_id(), "admin/Goods/goodsCategory?id={$id}")) {
            return false;
        }

        $oldCategory = Db::name("goods_category")->where(["delete_time" => 0])->where('id', $id)->find();

        if (empty($parentId)) {
            $newPath = '0';
        } else {
            $parentPath = Db::name("goods_category")->where(["delete_time" => 0])->where('id', intval($data['parent_id']))->value('path');
            if ($parentPath === false) {
                $newPath = false;
            } else {
                $newPath = "$parentPath,$parentId";
            }
        }
        if (empty($oldCategory) || $newPath == '') {
            $result = false;
        } else {
            $data['path'] = $newPath;
            $data['update_time'] = time();
            $result = Db::name("goods_category")->where('id', $id)->update($data);
        }
        return $result;
    }

    /**
     * Notes:返回商品分类
     * User: 
     * DateTime: 2021/3/5 15:00
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsNav()
    {
        $list = Db::name("goods_category")->field("id,category_name")->where("delete_time", 0)->select()->toArray();
        $res = array_column($list, "category_name", "id");
        return $res;
    }

}